<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport"
	content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">
<meta name="description" content="">
<meta http-equiv="x-dns-prefetch-control" content="on">
<title>创建搭车</title>
<link rel="stylesheet" href="../imgv2/css/default.min.css" />
<link href="../imgv2/css/css.css" rel="stylesheet" type="text/css">
</head>

<body class="graybg">
	<!--wrap start-->
	<section id="wrap">
		<section class="titlebar">当前位置</section>
		<section class="lh3 citylist whitebg">
			<ul class="listitem bottomline">
				<li class="itemico mtb"><i class="iconfont">&#xe606;</i></li>
				<li class="itemcon mtb"><a href="javascript:void(0);" id="txtJourneyDestination">获取当前位置</a></li>
				<li class="itemarrow mtb"><i class="iconfont">&#xe60c;</i></li>
			</ul>
		</section>
		<section class="message_info">给好友捎句话</section>
		<section class="message_form">
			<textarea rows="10" class="inputmore"></textarea>
		</section>
		<section class="citylist">
			<ul class="listitem h60 mt60">
				<button id="btnAddCar" class="bigbtn button"
					onClick="this.className='button_d bigbtn'"
					onmouseout="this.className='bigbtn button'">创建搭车</button>
			</ul>
		</section>
	</section>
	<div class="iframe-containter"></div>
	<!--wrap end-->
</body>
<script src="../jsv2/jquery-1.10.1.min.js"></script>
<script
	src="http://webapi.amap.com/maps?v=1.3&key=57c58c7b1f94514317df97e3a985962c"></script>
<script src="../jsv2/common.js"></script>
<script src="../jsv2/lib/json3.min.js"></script>
<script src="../jsv2/PageValueValidate.js"></script>
<script src="../jsv2/lib/QueryStringParser.js"></script>
<script src="../jsv2/jsonMsg.js"></script>
<script src="../jsv2/journey/operateData.js"></script>
<script>

var mapObj;
var windowsArr = [];
var marker = [];
var markers = [];
var geolocation;


function setLocation() {
	
    if (geolocation) {
       // geolocation.getCurrentPosition();
        geolocation.watchPosition();
    }
    else {
        setTimeout(setLocation, 1000);
    }
}

function geoInit(isCenter) {
    geolocation = new AMap.Geolocation({
        enableHighAccuracy: true, //是否使用高精度定位，默认:true  
        timeout: 100000,          //超过10秒后停止定位，默认：无穷大  
        maximumAge: 0,           //定位结果缓存0毫秒，默认：0  
        convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true  
        showButton: false,        //显示定位按钮，默认：true  
        buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角  
        buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)  
        showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true  
        markerOptions: { title: "locationIMG", offset: { x: -10, y: 20 }, icon: new AMap.Icon({ image: "http://webapi.amap.com/theme/v1.2/my_location.png", size: new AMap.Size(16, 16), imageOffset: { x: -24, y: -2} }) },
        showCircle: false,        //定位成功后用圆圈表示定位精度范围，默认：true  
        panToLocation: isCenter,     //定位成功后将定位到的位置作为地图中心点，默认：true  
        zoomToAccuracy: true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false  
    });
    mapObj.addControl(geolocation);
    geoSuccessListener = AMap.event.addListener(geolocation, 'complete', OnComplete); //返回定位信息,初始时定位后设为地图中心点  
    geoErrorListener = AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息  
}

function inputTxt(txtValue) {

  var forbidChar = new Array("@", "#", "$", "^", "&", "*", "……", "￥", "\"", "’", "'");
  for (var i = 0; i < forbidChar.length; i++) {
      if (txtValue.indexOf(forbidChar[i]) >= 0) {
          alert("您输入的信息中含有非法字符: " + forbidChar[i] + " 请更正！");
          return true;
      }
  }
  return false;;
}

function getStrLength(strValue) {
  var strLength = strValue.length;
  for (var j = 0; j < strValue.length; j++) {
      if (strValue.charCodeAt(j) > 255) {
          strLength++;
      }
  }
  return strLength;
}

function strDateTime(str)
{
	var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
	var r = str.match(reg);
	if(r==null)return false;
	var d= new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]);
	return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]);
}

var r = /^\+?[1-9][0-9]*$/;　　//正整数 

function validIntField(fieldName,displayName,fieldLength){
	var name = document.getElementById(fieldName).value; 
	if(name==null || name.trim()==""){
	alert("请输入"+displayName+".");
	document.getElementById(fieldName).select();
	return false;	
	}
	if(getStrLength(name)>fieldLength){
	alert(displayName+"长度不能超过"+fieldLength+".");
	document.getElementById(fieldName).select();
	return false;	
	}
	if(!r.test(name)){
	alert(displayName+"必须是整数.");
	document.getElementById(fieldName).select();
	return false;	
	}
	return true;
}

var f = /^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$/;
function validFloatField(fieldName,displayName,fieldLength){
	var name = document.getElementById(fieldName).value; 
	if(name==null || name.trim()==""){
	alert("请输入"+displayName+".");
	document.getElementById(fieldName).select();
	return false;	
	}
	if(getStrLength(name)>fieldLength){
	alert(displayName+"长度不能超过"+fieldLength+".");
	document.getElementById(fieldName).select();
	return false;	
	}
	if(isNaN(name)){
	alert(displayName+"必须是数字.");
	document.getElementById(fieldName).select();
	return false;	
	}
	return true;
}

function validField(fieldName,displayName,fieldLength){
	var name = document.getElementById(fieldName).value; 
	if(name==null || name.trim()==""){
		alert("请输入"+displayName+".");
		document.getElementById(fieldName).select();
		return false;	
	}
	if(getStrLength(name)>fieldLength){
		alert(displayName+"长度不能超过"+fieldLength+".");
		document.getElementById(fieldName).select();
		return false;	
	}	
	if(inputTxt(name)){
		document.getElementById(fieldName).select();
		return false;		
	}
	return true;	
}

/* 
*解析定位错误信息 
*/
function onError(data) {
    var str = '定位失败,';
    str += '错误信息：'
    switch (data.info) {
        case 'PERMISSION_DENIED':
            str += '浏览器阻止了定位操作';
            break;
        case 'POSITION_UNAVAILBLE':
            str += '无法获得当前位置';
            break;
        case 'TIMEOUT':
            str += '定位超时';
            break;
        default:
            str += '未知错误';
            break;
    }
    setLocation();
};

function geoRemove() {
    mapObj.removeControl(geolocation);
    AMap.event.removeListener(geoSuccessListener);
    AMap.event.removeListener(geoErrorListener);
    if ($("div[title='locationIMG']")) {
        $("div[title='locationIMG']").parent().remove();
    }
}

var _lat, _lng;

function OnComplete(data) {
	/*
	var lng, lat;
	lng = data.position.getLng();
	lat = data.position.getLat(); 
	*/
	//alert('complete');
	
	_lng = data.position.getLng();
	_lat = data.position.getLat(); 
	lnglatXY = new AMap.LngLat(data.position.getLng(),data.position.getLat());
	var nickName = $('#nickname').text();
	var imageURL = $('#mines').find('img').attr('src');
	geocoder();
	setMemberLocation(openId, data.position.getLng(), data.position.getLat(), imageURL, '1', 20,nickName);

}

var lnglatXY = null;
var destinationName = "";
function geocoder() {
    var MGeocoder;
    //加载地理编码插件
    AMap.service(["AMap.Geocoder"], function() {        
        MGeocoder = new AMap.Geocoder({ 
            radius: 1000,
            extensions: "all"
        });
        //逆地理编码
        MGeocoder.getAddress(lnglatXY, function(status, result){
        	if(status === 'complete' && result.info === 'OK'){
        		geocoder_CallBack(result);
        	}
        });
    });
}

//回调函数
function geocoder_CallBack(data) {
    //返回地址描述
    destinationName = data.regeocode.formattedAddress;
}  

function getExistsInMarkers(titleOpenID) {
    for (var i = 0; i < markers.length; i++) {
        var m = markers[i];
        if (m.getTitle() === titleOpenID) {
            return m;
        }
    }
    return null;
}


function setMemberLocation(_oID, _lng, _lat, _imageUrl, _isLeader, currentMember,nickNameIn) {
	if (!_imageUrl || _imageUrl=='') {
		return;
	}
	var _m = getExistsInMarkers(_oID);
	if (_m) {
	    if (currentMember > 1) {
	        _m.setzIndex(currentMember);
	    }
	    _m.setMap(mapObj);
	    _m.setPosition(new AMap.LngLat(_lng, _lat));
	}
	else {
	    var marker = new AMap.Marker({});
	
	    //自定义点标记内容     
	    var markerContent = document.createElement("div");
	    markerContent.className = "user_popup";
	
	    //头像
	    var markerContentDiv2 = document.createElement("div");
	    markerContentDiv2.className = "user_img_blue";
	    
	    var markerP2 = document.createElement("p");
	    var markerImg2 = document.createElement("img");
	    markerImg2.src = _imageUrl !== null && _imageUrl !== "" ? _imageUrl : "/Content/images/CO_02_Icon05_Norm.png";
	    markerImg2.width = 50;
	    markerImg2.height = 50;
	    markerP2.appendChild(markerImg2);
	    markerContentDiv2.appendChild(markerP2);
	    
	    var markerP22 = document.createElement("p");
	    markerP22.className = "user_popup_name";
	    markerP22.innerHTML=nickNameIn;
	    markerContentDiv2.appendChild(markerP22);
	
	    markerContent.appendChild(markerContentDiv2);
	    
	    var markerContentDiv3 = document.createElement("div");
	    markerContentDiv3.className = "downarrow";	
	    var markerImg3 = document.createElement("img");
	    markerImg3.src = "img/arrow_popup_blue.png";
	    
	    markerContentDiv3.appendChild(markerImg3);
	    markerContent.appendChild(markerContentDiv3);
	
	    if (currentMember > 1) {
	        marker.setzIndex(currentMember);
	    }
	
	    marker.setTitle(_oID)
	    marker.setContent(markerContent); //更新点标记内容
	    marker.setPosition(new AMap.LngLat(_lng, _lat)); //更新点标记位置                    
	    marker.setMap(mapObj);
			mapObj.setZoomAndCenter(14, new AMap.LngLat(_lng, _lat));
			mapObj.setFitView();
	    markers.push(marker);
	}
} 


function mapInit(center) {
    mapObj = new AMap.Map('iCenter', { level: 15 });
    
    mapObj.plugin(["AMap.ToolBar"],function(){		
			toolBar = new AMap.ToolBar();
			mapObj.addControl(toolBar);		
		});
		
    mapObj.plugin('AMap.Geolocation', function () {
        geoInit(false);
    });

};
 
//输入提示
function autoSearch() {
    var keywords = document.getElementById("keyword").value;
    var cityName = document.getElementById("city").value;
    if(cityName==null || cityName.trim()==""){
    	alert("请先输入城市!");
    	return false;	
    }
    var auto;
    //加载输入提示插件
        AMap.service(["AMap.Autocomplete"], function() {
        var autoOptions = {
            city: cityName //城市，默认全国
        };
        auto = new AMap.Autocomplete(autoOptions);
        //查询成功时返回查询结果
        if ( keywords.length > 0) {
            auto.search(keywords, function(status, result){
            	autocomplete_CallBack(result);
            });
        }
        else {
            document.getElementById("result1").style.display = "none";
        }
    });
}
 
//输出输入提示结果的回调函数
function autocomplete_CallBack(data) {
    var resultStr = "";
    var tipArr = data.tips;
    if (tipArr&&tipArr.length>0) {                 
        for (var i = 0; i < tipArr.length; i++) {
            resultStr += "<div id='divid" + (i + 1) + "' onmouseover='openMarkerTipById(" + (i + 1)
                        + ",this)' onclick='selectResult(" + i + ")' onmouseout='onmouseout_MarkerStyle(" + (i + 1)
                        + ",this)' style=\"font-size: 13px;cursor:pointer;padding:5px 5px 5px 5px;\"" + "data=" + tipArr[i].adcode + ">" + tipArr[i].name + "<span style='color:#C1C1C1;'>"+ tipArr[i].district + "</span></div>";
        }
    }
    else  {
        resultStr = " π__π 亲,人家找不到结果!<br />要不试试：<br />1.请确保所有字词拼写正确<br />2.尝试不同的关键字<br />3.尝试更宽泛的关键字";
    }
    document.getElementById("result1").curSelect = -1;
    document.getElementById("result1").tipArr = tipArr;
    document.getElementById("result1").innerHTML = resultStr;
    document.getElementById("result1").style.display = "block";
}
 
//输入提示框鼠标滑过时的样式
function openMarkerTipById(pointid, thiss) {  //根据id打开搜索结果点tip 
    thiss.style.background = '#CAE1FF';
}
 
//输入提示框鼠标移出时的样式
function onmouseout_MarkerStyle(pointid, thiss) {  //鼠标移开后点样式恢复 
    thiss.style.background = "";
}
 
//从输入提示框中选择关键字并查询
function selectResult(index) {
    if(index<0){
        return;
    }
    if (navigator.userAgent.indexOf("MSIE") > 0) {
        document.getElementById("keyword").onpropertychange = null;
        document.getElementById("keyword").onfocus = focus_callback;
    }
    //截取输入提示的关键字部分
    var text = document.getElementById("divid" + (index + 1)).innerHTML.replace(/<[^>].*?>.*<\/[^>].*?>/g,"");
	var cityCode = document.getElementById("divid" + (index + 1)).getAttribute('data');
    document.getElementById("keyword").value = text;
    document.getElementById("result1").style.display = "none";
    //根据选择的输入提示关键字查询
    mapObj.plugin(["AMap.PlaceSearch"], function() {       
        var msearch = new AMap.PlaceSearch();  //构造地点查询类
        AMap.event.addListener(msearch, "complete", placeSearch_CallBack); //查询成功时的回调函数
		msearch.setCity(cityCode);
        msearch.search(text);  //关键字查询查询
    });
}
 
//定位选择输入提示关键字
function focus_callback() {
    if (navigator.userAgent.indexOf("MSIE") > 0) {
        document.getElementById("keyword").onpropertychange = autoSearch;
   }
}
 
//输出关键字查询结果的回调函数
function placeSearch_CallBack(data) {
    //清空地图上的InfoWindow和Marker
    windowsArr = [];
    marker     = [];
    mapObj.clearMap();
    var resultStr1 = "";
    var poiArr = data.poiList.pois;
    var resultCount = poiArr.length;
    for (var i = 0; i < 1; i++) {
    	latLon = poiArr[i].location;
        resultStr1 += "<div id='divid" + (i + 1) + "' onmouseover='openMarkerTipById1(" + i + ",this)' onmouseout='onmouseout_MarkerStyle(" + (i + 1) + ",this)' style=\"font-size: 12px;cursor:pointer;padding:0px 0 4px 2px; border-bottom:1px solid #C1FFC1;\"><table><tr><td><img src=\"http://webapi.amap.com/images/" + (i + 1) + ".png\"></td>" + "<td><h3><font color=\"#00a6ac\">名称: " + poiArr[i].name + "</font></h3>";
            resultStr1 += TipContents(poiArr[i].type, poiArr[i].address, poiArr[i].tel) + "</td></tr></table></div>";
            addmarker(i, poiArr[i]);
    }
    mapObj.setFitView();
    //document.getElementById("result").innerHTML = resultStr1;
    //document.getElementById("result").style.display = "block";
}
 
//鼠标滑过查询结果改变背景样式，根据id打开信息窗体
function openMarkerTipById1(pointid, thiss) {
    this.style.background = '#CAE1FF';
    windowsArr[pointid].open(mapObj, marker[pointid]);
}
 
//添加查询结果的marker&infowindow   
function addmarker(i, d) {
    var lngX = d.location.getLng();
    var latY = d.location.getLat();
    var markerOption = {
        map:mapObj,
        icon:"http://webapi.amap.com/images/" + (i + 1) + ".png",
        position:new AMap.LngLat(lngX, latY)
    };
    var mar = new AMap.Marker(markerOption);         
    marker.push(new AMap.LngLat(lngX, latY));
 
    var infoWindow = new AMap.InfoWindow({
        content:"<h3><font color=\"#00a6ac\">  " + (i + 1) + ". " + d.name + "</font></h3>" + TipContents(d.type, d.address, d.tel),
        size:new AMap.Size(300, 0),
        autoMove:true, 
        offset:new AMap.Pixel(0,-30)
    });
    windowsArr.push(infoWindow);
    var aa = function (e) {infoWindow.open(mapObj, mar.getPosition());};
    AMap.event.addListener(mar, "click", aa);
}
 
//infowindow显示内容
function TipContents(type, address, tel) {  //窗体内容
    if (type == "" || type == "undefined" || type == null || type == " undefined" || typeof type == "undefined") {
        type = "暂无";
    }
    if (address == "" || address == "undefined" || address == null || address == " undefined" || typeof address == "undefined") {
        address = "暂无";
    }
    if (tel == "" || tel == "undefined" || tel == null || tel == " undefined" || typeof address == "tel") {
        tel = "暂无";
    }
    var str = "  地址：" + address + "<br />  电话：" + tel + " <br />  类型：" + type;
    return str;
}
function keydown(event){
    var key = (event||window.event).keyCode;
    var result = document.getElementById("result1")
    var cur = result.curSelect;
    if(key===40){//down
        if(cur + 1 < result.childNodes.length){
            if(result.childNodes[cur]){
                result.childNodes[cur].style.background='';
            }
            result.curSelect=cur+1;
            result.childNodes[cur+1].style.background='#CAE1FF';
            document.getElementById("keyword").value = result.tipArr[cur+1].name;
        }
    }else if(key===38){//up
        if(cur-1>=0){
            if(result.childNodes[cur]){
                result.childNodes[cur].style.background='';
            }
            result.curSelect=cur-1;
            result.childNodes[cur-1].style.background='#CAE1FF';
            document.getElementById("keyword").value = result.tipArr[cur-1].name;
        }
    }else if(key === 13){
        var res = document.getElementById("result1");
		if(res && res['curSelect'] !== -1){
			selectResult(document.getElementById("result1").curSelect);
		}
    }else{
        autoSearch();
    }
}

function getPageSize() {
    var xScroll, yScroll;
    if (window.innerHeight && window.scrollMaxY) {
        xScroll = window.innerWidth + window.scrollMaxX;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else {
        if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac    
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari 
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
        }
    }

    var windowWidth, windowHeight;
    if (self.innerHeight) { // all except Explorer    
        if (document.documentElement.clientWidth) {
            windowWidth = document.documentElement.clientWidth;
        } else {
            windowWidth = self.innerWidth;
        }
        windowHeight = self.innerHeight;
    } else {
        if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode   
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        } else {
            if (document.body) { // other Explorers   
                windowWidth = document.body.clientWidth;
                windowHeight = document.body.clientHeight;
            }
        }
    }       

    // for small pages with total height less then height of the viewport  
    if (yScroll < windowHeight) {
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }    

    // for small pages with total width less then width of the viewport   
    if (xScroll < windowWidth) {
        pageWidth = xScroll;
    } else {
        pageWidth = windowWidth;
    }
    arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight);
    return arrayPageSize;
}


var latLon = "";
var openId = queryString.getParam("openid");
var pickupId = "";
function createTrip(){
	/*
	if(_lat == ""){
		alert("无法获取你的位置");
		return false;	
	}
	
	if(String(_lng).indexOf(",")<0){
		alert("无法获取你的位置");
		return false;	
	} */
	if(_lat==null || _lat==""){
		alert("获取位置中,请稍后。");
		return false;	
	}
	var loc = {
		Latitude: parseFloat(_lat)*1000000,
		Longitude: parseFloat(_lng)*1000000	
	};

	var destination = {
		Name: $("#keyword").val(),  
    City: $("#city").val(),
		Loc : loc
	};
	
	if(!validField("title","搭车请求",20))
		return false;
	
	if($("#friends").val()=='0'){
		alert("请先选择一个好友！");
		return false;	
	}
	var dataStr = {   
        Title: $("#title").val(),  
        Loc: loc,  
        Destination: destinationName,
        Receiver:$("#friends").val()
    };  


	bidgeToWeixin(openId, 'CreatePickup', dataStr, function(data, status, xhr) {  
		//Do Anything After get Return data  
		pickupId = data.portalResp.Data.PickupID+"";
		document.getElementById("popupMain").style.display="";	
		var returnBack = fetchPickupInfo();
		var intervalId;
		if(returnBack=='1' || returnBack=="3"){
				if(returnBack=="3"){
					alert("您的好友解决了您的搭车请求，请再次联系或者选择另外一个好友尝试！");
					clearInterval(intervalId);
					//window.location.reload();	
				}
		}else{
				intervalId = setInterval(fetchPickupInfo, 10000);
		}
	});	 
}

function fetchPickupInfo(){
	var dataStr = {
		PickupID: 	pickupId
	};
	bidgeToWeixin(openId, 'PickupDetail', dataStr, function(data, status, xhr) { 
		if(data.portalResp.Data.Status=='1'){
			window.location.href="view_car.html?openid="+openId+'&pickupid='+pickupId;	
		}
		return data.portalResp.Data.Status;
	});	
}

var nickName,imageURL;

$(document).ready(function(){  	
	if(openId==null || openId==""){
		return false;	
	}else{
		var dataStr = {};//{Online: 1};	

		bidgeToWeixin(openId, 'ListFriends', dataStr, function(data, status, xhr) {  
	        $.each(data.portalResp.Data.Profiles, function(index){  
	            $("#friends").append("<option value='"+data.portalResp.Data.Profiles[index].OpenID+"'>"+data.portalResp.Data.Profiles[index].NickName+"</option>" );  
	        }); 	        
	        dataStr = {
						OpenID: 	openId+""
					};	
					bidgeToWeixin(openId, 'UserDetail', dataStr,  function(data, status, xhr) {  
				        $("#mines").html("");	
						var url = data.portalResp.Data.Profiles.ImageURL;
						if(url.substring(url.length-3)=="/64"){
							url = url.substring(0,url.length-3)+"/46";
          				}
						$("#mines").html("<img src='"+url+"'  class='user_pic'>");	
						
						$("#nickname").html("");	
						$("#nickname").html(data.portalResp.Data.Profiles.NickName);	
		        
				});
			}); 
	}
	
});
setLocation();
</script>
</html>